const http = require("http");
const url = require("url");
const path = require("path");
const fs = require("fs");
const httpProxy = require('http-proxy');
const dotenv = require('dotenv')
// import http from "http";
// import url from "url";
// import path from "path";
// import fs from "fs";

//读取.env环境变量
dotenv.config();
//读取环境变量
const { STATIC_PATH, PORT, PROXYS } = process.env;
console.log({ STATIC_PATH, PORT, PROXYS });
//将PROXYS转换为数组
const proxyEnv = PROXYS ? JSON.parse(PROXYS) : null;

let args = process.argv.splice(2);
let port = PORT || 9999;
if (args.length && !isNaN(args[0])) {
    port = parseInt(args[0]);
}
const config = {
    staticPath: STATIC_PATH || "./public",
    listen_port: port,
    proxy: proxyEnv || [{
        path: '/jshERP-boot',
        target: 'http://localhost:8994',
    }, {
        path: '/apo',
        target: 'http://localhost:8994',
    }],
    defaultFile: ["index.html", "index.htm", "default.htm", "default.html", "home.html"],
    gzip: true,
    cacheSecond: 172800,
    isHistory: true,
    contentType: {
        csv: "text/csv",
        css: "text/css",
        gif: "image/gif",
        html: "text/html",
        ico: "image/x-icon",
        jpeg: "image/jpeg",
        jpg: "image/jpeg",
        js: "text/javascript",
        json: "application/json",
        pdf: "application/pdf",
        png: "image/png",
        svg: "image/svg+xml",
        swf: "application/x-shockwave-flash",
        tiff: "image/tiff",
        txt: "text/plain",
        wav: "audio/x-wav",
        wma: "audio/x-ms-wma",
        wmv: "video/x-ms-wmv",
        xml: "text/xml",
    },
};


const etag = 'df551425fcc55e4d42a1487' + new Date().getTime();
const proxy = httpProxy.createProxyServer({});
const app = http
    .createServer(function (request, response) {
        var pathName = url.parse(request.url).pathname;
        var extName = path.extname(pathName).toLowerCase(); // .js
        var fullPath = config.staticPath + pathName;
        var extName2 = extName.replace(".", "");
        if (!extName && pathName.slice(-1) != "/") {
            pathName += "/";
        }
        console.log("pathName", pathName, "extName", extName, "fullPath", fullPath);
        if (config.proxy && config.proxy.length) {
            for (const p of config.proxy) {
                if (pathName.indexOf(p.path) == 0) {
                    proxy.web(request, response, {
                        target: p.target,
                        changeOrigin: true
                    });
                    console.log(pathName, "=proxy=>", p.target + pathName);
                    return;
                }
            }
        }


        // var folders = path.dirname(pathName);
        // var folderArr = folders.split("\\").filter((str) => str != "");
        // var firstFolder = folderArr.length == 0 ? "" : folderArr[0];

        // console.log({
        //     "request.url": request.url,
        //     pathName,
        //     fullPath,
        //     extName,
        //     extName2,
        //     fileName,
        //     fileName2,
        //     folders,
        //     folderArr,
        //     firstFolder
        // });

        if (!extName) {
            var isfix = false;
            for (var i = 0; i < config.defaultFile.length; i++) {
                if (fs.existsSync(fullPath + config.defaultFile[i])) {
                    fullPath = fullPath + config.defaultFile[i];
                    isfix = true;
                    break;
                }
            }
            if (!isfix) {
                fullPath = fullPath + config.defaultFile[0];
            }
        }

        console.log(fullPath);
        if (!fs.existsSync(fullPath)) {
            if (config.isHistory) {
                pathName = "/index.html";
                fullPath = config.staticPath + pathName;
            } else {
                response.writeHead(400, { "Content-Type": "text/html" });
                response.end("<h1>404 not found<br />File " + pathName + "  not found.<h1>");
                return;
            }
        }
        fs.readFile(fullPath, "binary", function (err, file) {
            if (err) {
                response.writeHead(500, {
                    "Content-Type": "text/plain",
                });
                response.end(err.toString());
            } else {
                var _contentType = "text/html";
                if (extName2 && config.contentType[extName2]) {
                    _contentType = config.contentType[extName2];
                }
                const header = {
                    "Content-Type": _contentType,
                };
                // 增加允许跨域
                header["Access-Control-Allow-Credentials"] = "true";
                header["Access-Control-Allow-Origin"] = "*";
                header["Access-Control-Allow-Headers"] = "X-Requested-With";
                header["Access-Control-Allow-Methods"] = "PUT,POST,GET,DELETE,OPTIONS";
                if (config.cacheSecond && ['.js', '.css', '.png', '.jpg', '.jpeg', '.bmp', '.webp', '.svg', '.gif', '.ico', '.exif', '.ai', '.apng', '.avif', '.woff2'].includes(extName)) {
                    header['Cache-Control'] = 'public, max-age=' + config.cacheSecond;
                    header['Expires'] = new Date(Date.now() + (config.cacheSecond * 1000)).toUTCString();
                    header['ETag'] = etag;
                }
                response.writeHead(200, header);
                response.write(file, "binary");
                response.end();
            }
        });
    })
    .listen(config.listen_port);
app.timeout = 36000000; //10 hours
console.log("listing port %d .", config.listen_port);
